/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.controller;

import com.alibaba.fastjson2.JSON;
import com.je.document.exception.DocumentException;
import com.je.document.exception.DocumentExceptionEnum;
import com.je.document.model.FileBO;
import com.je.document.service.DocumentBusService;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 提供client使用的API
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/8/27
 */
@RestController
@RequestMapping(value = "/je/api/document")
public class DocumentApiController {

    @Autowired
    private DocumentBusService documentBusService;

    /**
     * 读取文件流
     *
     * @param fileKey  文件唯一标识
     */
    @RequestMapping(value = "/readFileStream", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<InputStream> readFileStream(String fileKey) {
        try {
            FileBO fileBO = documentBusService.readFile(fileKey);
            String fileName = URLEncoder.encode(fileBO.getRelName(), "UTF-8");
            InputStream inputStream = fileBO.getFile();
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_LENGTH,String.valueOf(inputStream.available()))
                    .header(HttpHeaders.CONTENT_TYPE, fileBO.getContentType())
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
                    .body(fileBO.getFile());
        } catch (DocumentException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DocumentException("文件查找错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
        }
    }

    /**
     * 读取缩略图流
     *
     * @param fileKey  文件唯一标识
     */
    @RequestMapping(value = "/readThumbnailStream", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<InputStream> readThumbnailStream(String fileKey) {
        try {
           InputStream inputStream = documentBusService.thumbnail(fileKey);
           return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_LENGTH,String.valueOf(inputStream.available()))
                    .header(HttpHeaders.CONTENT_TYPE,"image/jpeg")
                   .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=缩略图.jpg")
                    .body(inputStream);
        } catch (DocumentException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DocumentException("文件查找错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
        }
    }

    /**
     * 读取版本文件流
     *
     * @param fileKey  文件唯一标识
     */
    @RequestMapping(value = "/readVersionFileStream", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<InputStream> readVersionFileStream(String fileKey, String version) {
        try {
            FileBO fileBO = documentBusService.readFile(fileKey, version);
            String fileName = URLEncoder.encode(fileBO.getRelName(), "UTF-8");
            InputStream inputStream = fileBO.getFile();
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_LENGTH,String.valueOf(inputStream.available()))
                    .header(HttpHeaders.CONTENT_TYPE, fileBO.getContentType())
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
                    .body(fileBO.getFile());
        } catch (DocumentException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DocumentException("文件查找错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
        }
    }

    @RequestMapping(value = "/buildZip", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public ResponseEntity<InputStream> buildZip(String fileKeys) {
        try {
            InputStream zipInputStream = documentBusService.buildZip(parseList(fileKeys));
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_LENGTH,String.valueOf(zipInputStream.available()))
                    .header(HttpHeaders.CONTENT_TYPE, "application/zip")
                    .body(zipInputStream);
        } catch (DocumentException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DocumentException("构建zip流错误", DocumentExceptionEnum.DOCUMENT_ERROR, e);
        }
    }

    /**
     * 转换List
     *
     * @param str 待转换数据
     * @return java.util.List<java.lang.String>
     */
    private List<String> parseList(String str) {
        List<String> list = null;
        if (StringUtils.isNotBlank(str)) {
            list = JSON.parseArray(str, String.class);
        }
        return list;
    }

}